<template>
  <div class="inventory-report">
    <div class="page-header">
      <div class="header-left">
        <h2>库存统计</h2>
        <p>实时监控库存状况，分析库存趋势和预警</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="generateReport">
          <el-icon><Document /></el-icon>
          生成报告
        </el-button>
        <el-button type="success" @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 统计概览 -->
    <div class="stats-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon total">
                <el-icon><Box /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ inventoryStats.totalProducts }}</div>
                <div class="stat-label">总商品数</div>
                <div class="stat-trend up">
                  <el-icon><ArrowUp /></el-icon>
                  +{{ inventoryStats.totalGrowth }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon stock">
                <el-icon><Goods /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ inventoryStats.totalStock }}</div>
                <div class="stat-label">总库存量</div>
                <div class="stat-trend down">
                  <el-icon><ArrowDown /></el-icon>
                  -{{ inventoryStats.stockDecrease }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon warning">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ inventoryStats.lowStockCount }}</div>
                <div class="stat-label">库存预警</div>
                <div class="stat-trend up">
                  <el-icon><ArrowUp /></el-icon>
                  +{{ inventoryStats.warningGrowth }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon value">
                <el-icon><Money /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">¥{{ inventoryStats.totalValue }}</div>
                <div class="stat-label">库存总值</div>
                <div class="stat-trend up">
                  <el-icon><ArrowUp /></el-icon>
                  +{{ inventoryStats.valueGrowth }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-card>
        <el-form :model="filterForm" inline>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 250px"
            />
          </el-form-item>
          <el-form-item label="商品分类">
            <el-select
              v-model="filterForm.categoryId"
              placeholder="请选择分类"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="供应商">
            <el-select
              v-model="filterForm.supplierId"
              placeholder="请选择供应商"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="supplier in suppliers"
                :key="supplier.id"
                :label="supplier.name"
                :value="supplier.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="库存状态">
            <el-select
              v-model="filterForm.stockStatus"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
            >
              <el-option label="充足" value="sufficient" />
              <el-option label="正常" value="normal" />
              <el-option label="偏低" value="low" />
              <el-option label="缺货" value="out" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="resetFilter">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 图表分析 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <!-- 库存趋势图 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>库存趋势</span>
            </template>
            <div ref="stockTrendChart" class="chart-container"></div>
          </el-card>
        </el-col>
        
        <!-- 分类库存分布 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>分类库存分布</span>
            </template>
            <div ref="categoryDistributionChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 库存预警分析 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>库存预警分析</span>
            </template>
            <div ref="stockWarningChart" class="chart-container"></div>
          </el-card>
        </el-col>
        
        <!-- 供应商库存对比 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>供应商库存对比</span>
            </template>
            <div ref="supplierComparisonChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 库存详情表格 -->
    <div class="table-section">
      <el-card>
        <template #header>
          <div class="table-header">
            <span>库存详情</span>
            <div class="table-actions">
              <el-button type="primary" size="small" @click="showAddStock = true">
                <el-icon><Plus /></el-icon>
                入库
              </el-button>
              <el-button type="warning" size="small" @click="showOutStock = true">
                <el-icon><Minus /></el-icon>
                出库
              </el-button>
            </div>
          </div>
        </template>
        
        <el-table
          :data="inventoryList"
          v-loading="tableLoading"
          style="width: 100%"
          border
        >
          <el-table-column prop="productCode" label="商品编码" width="120" />
          <el-table-column prop="productName" label="商品名称" min-width="150" />
          <el-table-column prop="category" label="分类" width="100" />
          <el-table-column prop="supplier" label="供应商" width="150" />
          <el-table-column prop="currentStock" label="当前库存" width="100">
            <template #default="{ row }">
              <span :class="getStockClass(row.currentStock, row.minStock)">
                {{ row.currentStock }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="minStock" label="最低库存" width="100" />
          <el-table-column prop="maxStock" label="最高库存" width="100" />
          <el-table-column prop="unitPrice" label="单价" width="100">
            <template #default="{ row }">
              ¥{{ row.unitPrice }}
            </template>
          </el-table-column>
          <el-table-column prop="totalValue" label="库存价值" width="120">
            <template #default="{ row }">
              ¥{{ row.totalValue }}
            </template>
          </el-table-column>
          <el-table-column prop="lastUpdate" label="最后更新" width="180" />
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStockStatusType(row.currentStock, row.minStock)">
                {{ getStockStatusText(row.currentStock, row.minStock) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="viewDetail(row)">
                详情
              </el-button>
              <el-button type="warning" size="small" @click="editStock(row)">
                编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { 
  Document, 
  Download, 
  Search, 
  Refresh, 
  Plus, 
  Minus,
  Box,
  Goods,
  Warning,
  Money,
  ArrowUp,
  ArrowDown
} from '@element-plus/icons-vue'

export default defineComponent({
  name: 'InventoryReport',
  components: {
    Document,
    Download,
    Search,
    Refresh,
    Plus,
    Minus,
    Box,
    Goods,
    Warning,
    Money,
    ArrowUp,
    ArrowDown
  },
  setup() {
    const tableLoading = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(20)
    const total = ref(0)
    const showAddStock = ref(false)
    const showOutStock = ref(false)
    
    // 图表引用
    const stockTrendChart = ref(null)
    const categoryDistributionChart = ref(null)
    const stockWarningChart = ref(null)
    const supplierComparisonChart = ref(null)
    
    // 筛选表单
    const filterForm = reactive({
      dateRange: [],
      categoryId: null,
      supplierId: null,
      stockStatus: ''
    })
    
    // 库存统计数据
    const inventoryStats = reactive({
      totalProducts: 1250,
      totalGrowth: 5.2,
      totalStock: 45680,
      stockDecrease: 2.1,
      lowStockCount: 23,
      warningGrowth: 8.5,
      totalValue: '2,456,800',
      valueGrowth: 3.8
    })
    
    // 分类数据
    const categories = ref([
      { id: 1, name: '生鲜食品' },
      { id: 2, name: '饮料酒水' },
      { id: 3, name: '零食糖果' },
      { id: 4, name: '日用品' },
      { id: 5, name: '电子产品' }
    ])
    
    // 供应商数据
    const suppliers = ref([
      { id: 1, name: '绿色农场供应商' },
      { id: 2, name: '优质食品供应商' },
      { id: 3, name: '新鲜果蔬供应商' },
      { id: 4, name: '日用品供应商' }
    ])
    
    // 库存列表数据
    const inventoryList = ref([
      {
        productCode: 'P001',
        productName: '有机苹果',
        category: '生鲜食品',
        supplier: '绿色农场供应商',
        currentStock: 150,
        minStock: 50,
        maxStock: 500,
        unitPrice: 8.5,
        totalValue: 1275,
        lastUpdate: '2024-01-15 10:30:00'
      },
      {
        productCode: 'P002',
        productName: '有机胡萝卜',
        category: '生鲜食品',
        supplier: '绿色农场供应商',
        currentStock: 80,
        minStock: 100,
        maxStock: 300,
        unitPrice: 3.2,
        totalValue: 256,
        lastUpdate: '2024-01-15 09:15:00'
      },
      {
        productCode: 'P003',
        productName: '纯牛奶',
        category: '饮料酒水',
        supplier: '优质食品供应商',
        currentStock: 200,
        minStock: 80,
        maxStock: 400,
        unitPrice: 12.5,
        totalValue: 2500,
        lastUpdate: '2024-01-15 08:45:00'
      },
      {
        productCode: 'P004',
        productName: '面包',
        category: '零食糖果',
        supplier: '新鲜果蔬供应商',
        currentStock: 0,
        minStock: 20,
        maxStock: 150,
        unitPrice: 5.8,
        totalValue: 0,
        lastUpdate: '2024-01-15 07:30:00'
      }
    ])
    
    // 初始化图表
    const initCharts = () => {
      nextTick(() => {
        // 库存趋势图
        const stockTrend = echarts.init(stockTrendChart.value)
        stockTrend.setOption({
          title: { text: '近30天库存趋势' },
          tooltip: { trigger: 'axis' },
          xAxis: {
            type: 'category',
            data: ['1月1日', '1月5日', '1月10日', '1月15日', '1月20日', '1月25日', '1月30日']
          },
          yAxis: { type: 'value' },
          series: [{
            data: [45000, 46000, 45500, 45680, 45800, 45700, 45680],
            type: 'line',
            smooth: true,
            areaStyle: {}
          }]
        })
        
        // 分类库存分布
        const categoryDistribution = echarts.init(categoryDistributionChart.value)
        categoryDistribution.setOption({
          title: { text: '分类库存分布' },
          tooltip: { trigger: 'item' },
          series: [{
            type: 'pie',
            radius: '50%',
            data: [
              { value: 15000, name: '生鲜食品' },
              { value: 12000, name: '饮料酒水' },
              { value: 8000, name: '零食糖果' },
              { value: 6000, name: '日用品' },
              { value: 4680, name: '电子产品' }
            ]
          }]
        })
        
        // 库存预警分析
        const stockWarning = echarts.init(stockWarningChart.value)
        stockWarning.setOption({
          title: { text: '库存预警分析' },
          tooltip: { trigger: 'axis' },
          xAxis: { type: 'category', data: ['充足', '正常', '偏低', '缺货'] },
          yAxis: { type: 'value' },
          series: [{
            data: [850, 320, 57, 23],
            type: 'bar',
            itemStyle: {
              color: function(params) {
                const colors = ['#67C23A', '#E6A23C', '#F56C6C', '#F56C6C']
                return colors[params.dataIndex]
              }
            }
          }]
        })
        
        // 供应商库存对比
        const supplierComparison = echarts.init(supplierComparisonChart.value)
        supplierComparison.setOption({
          title: { text: '供应商库存对比' },
          tooltip: { trigger: 'axis' },
          xAxis: { type: 'category', data: ['绿色农场', '优质食品', '新鲜果蔬', '日用品'] },
          yAxis: { type: 'value' },
          series: [{
            data: [12000, 15000, 8000, 10680],
            type: 'bar'
          }]
        })
      })
    }
    
    // 筛选处理
    const handleFilter = () => {
      currentPage.value = 1
      loadData()
    }
    
    // 重置筛选
    const resetFilter = () => {
      Object.assign(filterForm, {
        dateRange: [],
        categoryId: null,
        supplierId: null,
        stockStatus: ''
      })
      currentPage.value = 1
      loadData()
    }
    
    // 加载数据
    const loadData = async () => {
      tableLoading.value = true
      try {
        // 模拟API请求
        await new Promise(resolve => setTimeout(resolve, 1000))
        total.value = inventoryList.value.length
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
                  tableLoading.value = true
      }
    }
    
    // 生成报告
    const generateReport = async () => {
      try {
        ElMessage.success('报告生成成功')
      } catch (error) {
        console.error('生成报告失败:', error)
        ElMessage.error('生成报告失败')
      }
    }
    
    // 导出数据
    const exportData = async () => {
      try {
        ElMessage.success('数据导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
      }
    }
    
    // 查看详情
    const viewDetail = (row) => {
      ElMessage.info(`查看商品详情: ${row.productName}`)
    }
    
    // 编辑库存
    const editStock = (row) => {
      ElMessage.info(`编辑库存: ${row.productName}`)
    }
    
    // 获取库存状态类型
    const getStockStatusType = (current, min) => {
      if (current === 0) return 'danger'
      if (current < min) return 'warning'
      if (current < min * 1.5) return 'info'
      return 'success'
    }
    
    // 获取库存状态文本
    const getStockStatusText = (current, min) => {
      if (current === 0) return '缺货'
      if (current < min) return '偏低'
      if (current < min * 1.5) return '正常'
      return '充足'
    }
    
    // 获取库存样式类
    const getStockClass = (current, min) => {
      if (current === 0) return 'stock-out'
      if (current < min) return 'stock-low'
      return 'stock-normal'
    }
    
    // 分页处理
    const handleSizeChange = (val) => {
      pageSize.value = val
      loadData()
    }
    
    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadData()
    }
    
    onMounted(() => {
      loadData()
      initCharts()
    })
    
    return {
      tableLoading,
      currentPage,
      pageSize,
      total,
      showAddStock,
      showOutStock,
      stockTrendChart,
      categoryDistributionChart,
      stockWarningChart,
      supplierComparisonChart,
      filterForm,
      inventoryStats,
      categories,
      suppliers,
      inventoryList,
      handleFilter,
      resetFilter,
      loadData,
      generateReport,
      exportData,
      viewDetail,
      editStock,
      getStockStatusType,
      getStockStatusText,
      getStockClass,
      handleSizeChange,
      handleCurrentChange
    }
  }
})
</script>

<style scoped>
.inventory-report {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left h2 {
  margin: 0 0 5px 0;
  color: #2563eb;
}

.header-left p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.stats-overview {
  margin-bottom: 20px;
}

.stat-card {
  .stat-content {
    display: flex;
    align-items: center;
    
    .stat-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      
      &.total {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
      }
      
      &.stock {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        color: white;
      }
      
      &.warning {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        color: white;
      }
      
      &.value {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        color: white;
      }
      
      .el-icon {
        font-size: 24px;
      }
    }
    
    .stat-info {
      flex: 1;
      
      .stat-number {
        font-size: 24px;
        font-weight: bold;
        color: #333;
        margin-bottom: 4px;
      }
      
      .stat-label {
        font-size: 14px;
        color: #666;
        margin-bottom: 4px;
      }
      
      .stat-trend {
        font-size: 12px;
        display: flex;
        align-items: center;
        
        &.up {
          color: #67C23A;
        }
        
        &.down {
          color: #F56C6C;
        }
        
        .el-icon {
          margin-right: 2px;
        }
      }
    }
  }
}

.filter-section {
  margin-bottom: 20px;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-card {
  .chart-container {
    height: 300px;
  }
}

.table-section {
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .table-actions {
    display: flex;
    gap: 10px;
  }
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.stock-out {
  color: #F56C6C;
  font-weight: bold;
}

.stock-low {
  color: #E6A23C;
  font-weight: bold;
}

.stock-normal {
  color: #67C23A;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-right {
    width: 100%;
    display: flex;
    gap: 10px;
  }
  
  .stats-overview {
    .el-col {
      margin-bottom: 20px;
    }
  }
  
  .charts-section {
    .el-col {
      margin-bottom: 20px;
    }
  }
}
</style> 